import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    websock: null,
    getMessage:null
  },
  getters: {
    onEvent(state) {
      //把 初始化定义的方法 返回出来
      return state.websock;
    }
  },
  mutations: {
    WEBSOCKET_INIT(state,data) {
      console.log("登录id:"+data.id);
      state.websock = new WebSocket(data.url);
      state.websock.onopen = function () {
        console.log("连接成功！");
        var dataContent = {
          action : 1,
          chatMsg: {
            sendUserId : data.id,
            acceptUserId : '',
            msg : 'ping',
            msgId : '111',
          },
        }
        //连接成功 发送数据，在后台将发送者的 id 和 channel 绑定起来
        state.websock.send(JSON.stringify(dataContent));
      }
      state.websock.onmessage = function (callBack) {
        console.log("ws接收！");
        console.log(callBack.data);
        state.getMessage=callBack.data;
        // state.eventlist.push({
        //   method:methodStr,
        //   data:JSON.parse(dataStr)
        // })
      }
      state.websock.οnerrοr=function(e) { //错误
        console.log("ws错误!");
        console.log(e);
      }
      state.websock.onclose=function(e) { //关闭
        console.log("ws关闭！");
        console.log(e);
      }
      state.websock.binaryType = "arraybuffer";
      //发送心跳包
      setInterval(function() {
        console.log("ws发送心跳！");
        //发送心跳检测
        var dataContent = {
          action : 4,
          chatMsg: {
            sendUserId : '',
            acceptUserId : '',
            msg : '发送心跳',
            msgId : '',
          },
          extand : null,
        }
        state.websock.send(JSON.stringify(dataContent));
      }, 30000)
    },
    WEBSOCKET_SEND(state, p) {
      console.log("ws发送:"+p);
      state.websock.send(p);
    },
    WEBSOCKET_ONMESSAGE(state, p) {
      console.log("收到消息:"+p);
      return  state.websock.onmessage(p);
    }
  },
  actions: {
    WEBSOCKET_INIT({commit},data) {
      commit('WEBSOCKET_INIT',data)
    },
    WEBSOCKET_SEND({commit}, p) {
      commit('WEBSOCKET_SEND', p)
    },
    WEBSOCKET_ONMESSAGE(state, p) {
      commit('WEBSOCKET_ONMESSAGE', p)
    }
  }
})
